<template>
  <div class="model-setting">
    <el-divider class="header-title">模型选择</el-divider>
    <div class="win-flex-row model-select">
      <el-form label-width="80px" class="flex-1" size="mini">
        <el-form-item label="模型模式:">
          <el-tabs v-model="singleDoubleModel" type="card" size="mini" class="model-tabs" @tab-click="handleTabChange">
            <el-tab-pane label="单模型" name="single"></el-tab-pane>
            <el-tab-pane label="双模型" name="double"></el-tab-pane>
            <el-tab-pane label="兼容模式" name="compatible"></el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="主播:">
          <div class="win-flex-row">
            <el-select filterable placeholder="主播" :disabled="!canUpdate" v-model="modelSetting.anchor"
              @change="changeModel('anchor', modelSetting.anchor)">
              <el-option :key="'anchorModelType_' + index" v-for="(item, index) in modelTypes" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
            <el-button style="margin-left: 10px;" type="warning" @click="testListening('anchor', modelSetting.anchor)"
              :disabled="!canUpdate">模型试听</el-button>
          </div>
        </el-form-item>
        <el-form-item label="小助理:">
          <div class="win-flex-row">
            <el-select filterable placeholder="小助理" :disabled="!canUpdate" v-model="modelSetting.assistant"
              @change="changeModel('assistant', modelSetting.assistant)">
              <el-option :key="'assistantModelType_' + index" v-for="(item, index) in modelTypes" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
            <el-button style="margin-left: 10px;" type="warning"
              @click="testListening('assistant', modelSetting.assistant)" :disabled="!canUpdate">模型试听</el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-button class="refreshModelBtn" :disabled="!canUpdate" type="primary" @click="getListModel">刷新模型</el-button>
      <el-button class="refreshModelBtn" :disabled="!canUpdate" type="danger" @click="refreshModel">重启模型</el-button>
    </div>
    <el-divider class="header-title">显卡配置</el-divider>
    <el-form label-width="200px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="总显存:">
            {{ gpuResult.gpuMemorySize }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="驱动版本:">
            {{ gpuResult.gpuDriverVersion }}
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <el-divider class="header-title">合成设置</el-divider>
    <el-form label-width="200px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="前k个采样(Top-k):">
            <el-input-number v-model="modelSetting.topK" :disabled="!canUpdate" :min="0" :max="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="累计概率采样(Top-p):">
            <el-input-number v-model="modelSetting.topP" :disabled="!canUpdate" :min="0" :max="1" :step="0.1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="语速:">
            <el-input-number v-model="modelSetting.speedFactor" :disabled="!canUpdate" :min="0.01" :max="2"
              :step="0.01" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重复惩罚:">
            <el-input-number v-model="modelSetting.repetitionPenalty" :disabled="!canUpdate" :min="0" :max="2"
              :step="0.1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="温度系数(Temperature):">
            <el-input-number v-model="modelSetting.temperature" :disabled="!canUpdate" :min="0" :max="1" :step="0.1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="种子码:">
            <el-input-number v-model="modelSetting.seed" :disabled="!canUpdate" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form> -->
  </div>
</template>

<script>
import { listModel, switchModel, testListening } from '@/api/bvmodel/bvmodel';
import { restartModel } from '@/api/common/assistant';
import { EventBus } from '@/event-bus.js';
import { getGpuInfo } from '@/api/common/assistant';
import { saveEntity, getConfigKey } from '@/api/sys/config';

export default {
  name: 'ModelSetting',
  data() {
    return {
      gpuResult: {},
      liveStatus: 0,
      modelTypes: [],
      singleDoubleModel: 'single',
      originalValue: '', // 保存当前模式
    };
  },
  created() {
    this.gpuInfo();
    this.getListModel();
    EventBus.$on("changeLiveStatus", (status) => {
      //开启了直播
      this.liveStatus = status;
    });
    getConfigKey('single.double.model').then(res => {
      this.singleDoubleModel = res.result.configValue;
      this.originalValue = res.result.configValue;
    })
  },
  beforeDestroy() {
    EventBus.$off('changeLiveStatus');
  },
  computed: {
    canUpdate() {
      return this.liveStatus === 0;
    },
    modelSetting() {
      return this.pageConfig.modelSetting;
    },
    pageConfig() {
      return this.$store.state.page.config;
    }
  },
  methods: {
    handleTabChange(tab) {
      getConfigKey('single.double.model').then(res => {
        this.originalValue = res.result.configValue;
      })
      this.$confirm(`您确定要开启${tab.label}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading(`开启${tab.label}中，请稍后...`);
        // 更新sysconfig表中的双模型开关状态
        saveEntity({
          id: 24,
          configValue: tab.name
        }).then(() => {
          this.$modal.closeLoading();
          this.$message({
            type: 'success',
            message: `开启${tab.label}成功`
          });
        }).catch(() => {
          this.$modal.closeLoading();
          this.$message({
            type: 'error',
            message: `开启${tab.label}失败`
          });
          // 恢复tab状态
          this.singleDoubleModel = this.originalValue;
        });
      }).catch(() => {
        // 取消操作，恢复tab状态
        this.singleDoubleModel = this.originalValue;
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    gpuInfo() {
      getGpuInfo().then(res => {
        if (res.code == 200) {
          this.gpuResult = res.result;
        }
      });
    },
    /**
     * 试听模型
     */
    testListening(playerType, modelName) {
      this.$modal.loading('生成中，请稍后...');
      testListening({ playerType, modelName }).then(res => {
        this.$modal.closeLoading();
      }).catch(err => {
      });
    },
    /**
     * 切换模型
     */
    changeModel(playerType, modelName) {
      this.$modal.loading('模型切换中，请稍后...');
      switchModel({ playerType, modelName }).then(res => {
        this.$message({
          message: '切换成功',
          type: 'success'
        });
        this.$modal.closeLoading();
      }).catch(err => {
        this.$message({
          message: '切换失败',
          type: 'error'
        });
        this.$modal.closeLoading();
      });
    },
    getListModel() {
      listModel().then(res => {
        if (res.result) {
          this.modelTypes = res.result.map(item => {
            return {
              label: item.modelName,
              value: item.modelName
            }
          });
        }
      });
    },
    refreshModel() {
      this.$modal.loading('模型重启中，请耐心等候...');
      restartModel().then(res => {
        this.$modal.closeLoading();
        this.$message({
          message: '刷新成功',
          type: 'success'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.model-select {
  .el-select {
    width: 80%;
  }

  .el-form {
    .el-form-item {
      &:last-child {
        margin-bottom: 0px !important;
      }
    }
  }

  .refreshModelBtn {
    margin-left: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.model-tabs {
  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 5px;

    &.is-active {
      color: #409eff;
      background-color: #ecf5ff;
      border-color: #409eff;
    }
  }
}
</style>
